package com.fa4j.common.web.util;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.method.HandlerMethod;

import java.lang.reflect.Method;
import java.util.Objects;

import static org.springframework.web.servlet.HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE;

public class RequestUtil {

    public static HttpServletRequest getRequest() {
        try {
            if (RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes requestAttributes) {
                return requestAttributes.getRequest();
            }
        } catch (Exception ignored) {
        }
        return null;
    }

    public static HandlerMethod getHandlerMethod() {
        HttpServletRequest request = getRequest();
        if (request != null && request.getAttribute(BEST_MATCHING_HANDLER_ATTRIBUTE) instanceof HandlerMethod hm) {
            return hm;
        }
        return null;
    }

    public static boolean isRequestMethod(Method method) {
        HandlerMethod hm = getHandlerMethod();
        // 拦截的类和 web 处理的类不是同一个，则不处理
        return hm != null && Objects.equals(hm.getMethod(), method);
    }
}
